package com.al.study.record.sort;

/**
 * Created by yuxi on 2017/9/2.
 */
public class MergeSort {
    private static int[] copy ;

    public static void main(String[] args) {
        int[] arr = {3, 3, 3, 3, 3, 3, 4, 3};
        int lo = 0;
        int hi = arr.length - 1;
        //create copy array
        copy = new int[arr.length];
        mergeSortToTop(arr, lo, hi);
        mergeSortToButtom(arr);
        for (int i : arr) {
            System.out.print(i + "  ");
        }

    }


    /**
     * 自顶而上的归并排序
     *
     * @param arr
     * @return
     */
    private static void mergeSortToButtom(int[] arr) {
        int N = arr.length;
        for (int sz = 1; sz <N ; sz = sz+sz) {
            for (int lo = 0; lo <N-sz ; lo+= sz+sz) {
                merge(arr,lo,lo+sz-1,Math.min(lo+sz+sz-1,N-1));
            }

        }
    }

    /**
     * 自顶而下的归并排序
     *
     * @param arr
     * @param lo
     * @param hi
     * @return
     */
    private static void mergeSortToTop(int[] arr, int lo, int hi) {
        if (lo >= hi) return;
        int mid = (lo + hi) / 2;
        mergeSortToTop(arr, lo, mid);
        mergeSortToTop(arr, mid + 1, hi);
        merge(arr, lo, mid, hi);
    }

    /**
     *排序
     * @param arr
     * @param lo
     * @param mid
     * @param hi
     */
    private static void merge(int[] arr, int lo, int mid, int hi) {
        int i= lo;
        int j = mid+1;
        // 将原数组copy到新的数组里
        for (int k = lo; k <=hi ; k++) {
            copy[k] = arr[k];
        }
        //分成两半进行排序
        for (int k = lo; k <=hi; k++) {
            if (i > mid) arr[k] = copy[j++];
            else if (j > hi) arr[k] = copy[i++];
            else if (arr[i] > arr[j]) arr[k] = copy[j++];
            else arr[k] = copy[i++];
        }
    }
}
